package com.yunxin.mybatisplus.utils;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: PageUtil
 * Package: com.yunxin.shweb.utils
 * Description: 内存使用MybatisPlus分页插件 模拟实现
 *
 * @Author sbx
 * @Create 2025/9/4 9:26
 */
public class MybatisPlusPageUtil {

    public static <T> Page<T> convertToPage(List<T> fullList, int currentPage, int pageSize) {

        if (fullList == null) {
            fullList = new ArrayList<>();
        }

        long total = fullList.size();
        // 计算总页数
        int pages = (int) Math.ceil((double) total / pageSize);
        pages = pages <= 0 ? 1 : pages;

        // 越界修正
        currentPage = Math.max(1, currentPage);
        currentPage = Math.min(currentPage, pages);

        // 计算分页边界
        int fromIndex = (currentPage - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, fullList.size());

        // 截取当前页数据
        List<T> pagedList = new ArrayList<>();
        if (fromIndex < fullList.size()) {
            pagedList = new ArrayList<>(fullList.subList(fromIndex, toIndex));
        }

        // 构造 MyBatis-Plus Page 对象
        Page<T> page = new Page<>();
        // 当前页数据
        page.setRecords(pagedList);
        // 总记录数
        page.setTotal(total);
        // 每页大小
        page.setSize(pageSize);
        // 当前页
        page.setCurrent(currentPage);
        // 总页数
        page.setPages(pages);
        return page;
    }
}
